/*
 * @Description: 生成 uniapp index
 * @Author: DHL
 * @Date: 2022-01-30 14:20:12
 * @LastEditors: DHL
 * @LastEditTime: 2023-03-03 15:05:58
 */

import { firstToUpperCase, firstToLowerCase, getAuthKey } from '../../utils/codeGenUtils'
import { stringUtils } from '@/utils/stringUtils'

export function createUniappIndex(codeGenConfig: any) {
  const classNameFirstToUpperCase = firstToUpperCase(codeGenConfig.className)
  const classNameFirstToLowerCase = firstToLowerCase(codeGenConfig.className)
  const apiPath = codeGenConfig.pagesApiPath
  const resName = classNameFirstToLowerCase
    .replace(/([A-Z])/g, '_$1')
    .trim()
    .replaceAll('_', '-')
    .toUpperCase()

  return `
<!--
 * @Description: ${codeGenConfig.genName} - 主页面
 * @Author: ${codeGenConfig.genAuthor}
 * @Date: ${codeGenConfig.createData}
 * @LastEditors: ${codeGenConfig.genAuthor}
 * @LastEditTime: ${codeGenConfig.createData}
-->
<template>
  <!-- #ifdef MP-WEIXIN -->
  <page-meta :page-style="'overflow:' + (popupShow ? 'hidden' : 'visible')"></page-meta>
  <!-- #endif -->

  <view class="tw-wrap list-wrap">
    <uni-swipe-action ref="swipeActionRef">
      <z-paging
        ref="pagingRef"
        use-virtual-list
        auto-show-back-to-top
        show-refresher-when-reload
        cell-height-mode="dynamic"
        :force-close-inner-list="true"
        safe-area-inset-bottom
        @virtualListChange="handleTableListChange"
        @query="handleSearch"
      >
        <template #top>
          <view class="header dropdown">
            <view class="search" @click="handleOpenSearch">
              <uni-search-bar :radius="100" placeholder="搜索" :readonly="true"></uni-search-bar>
            </view>
            <tw-dropdown
              ref="twDropdownRef"
              v-model:dropdownMenu="dropDownState.menu"
              @confirm="handleDropdownConfirm"
            >
            </tw-dropdown>
          </view>
        </template>

        <view
          class="card"
          v-for="(item, index) in tableList"
          :id="\`zp-id-\${item.zp_index}\`"
          :key="item.zp_index"
        >
          <tw-section type="circle" :title="item.id" titleFontSize="34rpx" padding="0px 16px">
          <uni-swipe-action-item
              :right-options="actions"
              @click="(e: any) => handleAction(item, e)"
            >
              <view @click="handleView(item)">
                ${getTableColumns(codeGenConfig.optionsJson.columns)}
              </view>
            </uni-swipe-action-item>
          </tw-section>
        </view>
      </z-paging>
    </uni-swipe-action>


    <!-- 查询弹框表单 -->
    <uni-popup ref="popupRef" type="top" @change="(e:any) => (popupShow = e.show)">
      <view class="search-popup-wrap">
        <scroll-view scroll-y="true" class="scroll-Y">
          <view class="form-wrap">
            <uni-forms ref="formRef" :modelValue="searchForm" label-position="top" label-width="120" border>
            ${getSearchForm(codeGenConfig.optionsJson.columns)}
            </uni-forms>
          </view>
        </scroll-view>

        <view class="footer">
          <uv-button shape="circle" size="normal" text="重置" @click="handleReset"></uv-button>
          <uv-button
            type="primary"
            size="normal"
            shape="circle"
            text="查询"
            @click="handleQuery"
          ></uv-button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
  import { onLoad } from '@dcloudio/uni-app'
  import { reactive, ref } from 'vue'
  import { assign, cloneDeep } from 'lodash-es'
  import { getUrlByName } from '@/hooks/bizPath'
  import { api${classNameFirstToUpperCase}LogicBatchDeleteByIds, api${classNameFirstToUpperCase}Search } from '@/${apiPath}/${classNameFirstToLowerCase}'


  //////////////////////////////////////////////////
  // 生命周期
  //////////////////////////////////////////////////
  onLoad(() => {})

  //////////////////////////////////////////////////
  // 查询条件
  //////////////////////////////////////////////////
  /**
   * 下拉筛选
   */
  const dropDownState = reactive({
    menu: [
      {
        title: '时间',
        type: 'sort',
        value: 'desc',
        prop: 'createDate'
      },
      {
        title: '新建',
        type: 'click',
        prop: 'add'
      }
    ]
  })

  /**
   * 下拉筛选组件
   */
  const twDropdownRef = ref()

  /**
   * 弹窗组件
   */
  const popupRef = ref()

  /**
   * 弹窗状态
   */
  const popupShow = ref(false)

  /**
   * 查询表单默认值
   */
  const searchFormDefault = {
    ${getField(codeGenConfig.optionsJson.columns)}
  }

  /**
   * 查询表单
   */
  const searchForm = reactive(cloneDeep(searchFormDefault))

  /**
   * 下拉筛选确认事件
   */
  function handleDropdownConfirm(v: any) {
    if (v.add) {
      uni.navigateTo({
        url: getUrlByName('${classNameFirstToLowerCase}Form', { action: 'add' }),
        events: {
          addEvent: function (data: any) {
            pagingRef.value.reload()
          }
        }
      })
    } else {
      pagingRef.value.reload()
    }
  }

  /**
   * 打开查询弹窗
   */
  function handleOpenSearch() {
    popupRef.value.open()
  }

  /**
   * 查询
   */
  function handleQuery() {
    pagingRef.value.reload()
    popupRef.value.close()
  }

  /**
   * 重置查询
   */
  function handleReset() {
    assign(searchForm, cloneDeep(searchFormDefault))
    pagingRef.value.reload()
    popupRef.value.close()
  }


  //////////////////////////////////////////////////
  // 列表
  //////////////////////////////////////////////////
  /**
   * 分页组件
   */
  const pagingRef = ref()

  /**
   * 虚拟列表数组
   */
  const tableList = ref([] as Array<any>)

  /**
   * 监听虚拟列表数组改变并赋值给virtualList进行重新渲染
   * @param vList
   */
  function handleTableListChange(vList: Array<any>) {
    tableList.value = vList
  }

  /**
   * 查询列表
   */
  function handleSearch(pageNo: any, pageSize: any) {
    const tddParams = twDropdownRef.value.getMenuValue()

    const params = {
      pageNum: pageNo,
      pageSize: pageSize,
      sort: 't.create_date',
      order: tddParams.createDate || 'desc'
    }

    assign(params, searchForm)

    api${classNameFirstToUpperCase}Search(params)
      .then((result) => {
        if (result?.success) {
          pagingRef.value.complete(result.data.list)
        }
      })
      .catch(() => {
        pagingRef.value?.complete(false)
      })
      .finally(() => {})
  }

  //////////////////////////////////////////////////
  // 滑动操作
  //////////////////////////////////////////////////
  /**
   * 滑动操作组件
   */
  const swipeActionRef = ref()

  /**
   * 滑动操作按钮
   */
  const actions = ref([
    {
      name: 'delete',
      text: '删除',
      style: {
        backgroundColor: '#e43d33'
      }
    },
    {
      name: 'edit',
      text: '编辑',
      style: {
        backgroundColor: '#f3a73f'
      }
    }
  ])

  /**
   * 滑动操作
   */
  function handleAction(row: any, e: any) {
    const {
      content: { name }
    } = e

    switch (name) {
      case 'edit':
        editFun(row)
        break
      case 'delete':
        deleteFun(row)
        break
    }
  }

  /**
   * 查看操作
   */
  function handleView(row: any) {
    uni.navigateTo({
      url: getUrlByName('${classNameFirstToLowerCase}Form', { action: 'view', id: row.id })
    })
  }

  /**
   * 编辑操作
   */
  function editFun(row: any) {
    uni.navigateTo({
      url: getUrlByName('${classNameFirstToLowerCase}Form', { action: 'edit', id: row.id }),
      events: {
        editEvent: function (data: any) {
          pagingRef.value.reload()
        }
      }
    })
  }

  /**
   * 删除操作
   */
  function deleteFun(row: any) {
    uni.showModal({
      title: '删除',
      content: '确定删除该条数据？',
      success: (res) => {
        if (res.confirm) {
          uni.showLoading({
            title: '删除中...'
          })
          api${classNameFirstToUpperCase}LogicBatchDeleteByIds(row.id)
            .then((result) => {
              uni.showToast({
                title: result?.message,
                icon: 'none'
              })

              if (result?.success) {
                swipeActionRef.value.closeAll()
                pagingRef.value.refresh()
              }
            })
            .catch(() => {})
            .finally(() => {
              uni.hideLoading()
            })
        }
      }
    })
  }
</script>

<style lang="scss" scoped>
  .tw-wrap {
    .search-popup-wrap {
      height: 50vh;
      background-color: #ffffff;
    }
  }
</style>
`
}

/**
 * 获取查询表单
 * @param columns
 */
function getSearchForm(columns: any) {
  let rtn: Array<string> = []

  columns.forEach((item: any) => {
    if (item.query) {
      rtn.push(
        `
              <uni-forms-item label="${item.javaComment}">
                ${getSearchComponent(item)}
              </uni-forms-item>
          `
      )
    }
  })
  return rtn.join('')
}

/**
 * 查询表单组件
 * @param item
 * @returns
 */
function getSearchComponent(item: any) {
  let rtn: Array<string> = []
  switch (item.componentType) {
    case 'input':
      if (item.queryWay === 'between') {
        rtn.push(``)
      } else {
        rtn.push(
          `<uni-easyinput v-model="searchForm.${item.javaField}" placeholder="" :inputBorder="false" />`
        )
      }
      break
    case 'textarea':
      if (item.queryWay === 'between') {
        rtn.push(``)
      } else {
        rtn.push(
          `<uni-easyinput type="textarea" autoHeight v-model="searchForm.${item.javaField}" placeholder=""  />`
        )
      }
      break
    case 'select':
      if (item.queryWay === 'between') {
        rtn.push(``)
      } else {
        rtn.push(
          `<uni-data-select v-model="searchForm.${item.javaField}" placeholder="" :localdata="[{ value: 0, text: '开发实现' }]"></uni-data-select>`
        )
      }
      break
    case 'inputNumber':
      if (item.queryWay === 'between') {
        rtn.push(``)
      } else {
        rtn.push(
          `<uni-easyinput type="digit" autoHeight v-model="searchForm.${item.javaField}" placeholder="" :inputBorder="false" />`
        )
      }
      break
    case 'radio':
      rtn.push(
        `<uni-data-checkbox v-model="searchForm.${item.javaField}" :localdata="[{text:'男', value:0}, {text:'女', value: 1}]"></uni-data-checkbox>`
      )
      break
    case 'checkbox':
      rtn.push(
        `<uni-data-checkbox multiple v-model="searchForm.${item.javaField}" :localdata="[{text:'男', value:0}, {text:'女', value: 1}]"></uni-data-checkbox>`
      )
      break
    case 'datePicker':
      if (item.queryWay === 'between') {
        rtn.push(``)
      } else {
        rtn.push(`<tw-date v-model="searchForm.${item.javaField}" placeholder=""></tw-date>`)
      }
      break
    case 'dateTimePicker':
      if (item.queryWay === 'between') {
        rtn.push(``)
      } else {
        rtn.push(
          `<uni-datetime-picker type="datetime" return-type="string" v-model="searchForm.${item.javaField}" :border="false"/>`
        )
      }
      break
    case 'timePicker':
      if (item.queryWay === 'between') {
        rtn.push(``)
      } else {
        rtn.push(
          `<tw-date-time v-model="searchForm.${item.javaField}" placeholder=""></tw-date-time>`
        )
      }
      break
    case 'timeSelect':
      if (item.queryWay === 'between') {
        rtn.push(``)
      } else {
        rtn.push(
          `<tw-date-time v-model="searchForm.${item.javaField}" placeholder=""></tw-date-time>`
        )
      }
      break
    case 'switch':
      rtn.push(``)
      break
    case 'upload':
      rtn.push(``)
      break
    case 'dataDic':
      rtn.push(
        `<tw-dic v-model="searchForm.${item.javaField}" dicKey="${item.dataDic}" placeholder="" />`
      )
      break
    case 'money':
      if (item.queryWay === 'between') {
        rtn.push(``)
      } else {
        rtn.push(``)
      }
      break
    default:
      break
  }
  return rtn.join('')
}

/**
 * 获取表格列
 * @param columns
 */
function getTableColumns(columns: any) {
  let field: Array<string> = []

  columns.forEach((item: any) => {
    if (item.list) {
      if (stringUtils.isNotEmpty(item.dataDic)) {
        field.push(`<view class="txt">
          ${item.javaComment}：<tw-dic-name dicKey="${item.dataDic}" :dicValue="item.${item.javaField}" />
          </view>
          `)
      } else {
        field.push(`<view class="txt">${item.javaComment}：{{ item.${item.javaField} }}</view>
          `)
      }
    }
  })

  return field.join('')
}

/**
 * 获取字段
 * @param columns
 */
function getField(columns: any) {
  let field: Array<string> = []

  let searchArray: any[] = []

  columns.forEach((item: any) => {
    if (item.query) {
      searchArray.push(item)
    }
  })
  for (let i = 0; i < searchArray.length; i++) {
    const item = searchArray[i]

    if (i === searchArray.length - 1) {
      field.push(`${item.javaField}: null  // ${item.javaComment}`)
    } else {
      field.push(`${item.javaField}: null,  // ${item.javaComment}
      `)
    }
  }

  return field.join('')
}
